<template>
  <div class="main">
    <div class="search">
      <label>订单搜索：</label>
      <el-input v-model="or.orderNo" style="width: 240px" placeholder="请输入订单号 " clearable>
      </el-input>
      <el-button type="primary" @click="search" style="margin-left: 10px;">查询</el-button>
      <!-- <el-button class="button" :icon="Delete" @click="deleteRows">批量删除</el-button> -->
    </div>
    <div class="data">
      <div class="gird">
        <el-table :data="tableData" border style="width: 100%" :header-cell-style="{ textAlign: 'center' }"
                  :cell-style="{ textAlign: 'center' }" ref="tableRef" v-loading="loading">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="编号" width="60" />
          <el-table-column prop="orderNo" label="订单号" width="200" />
          <el-table-column prop="memberId" label="会员账号" width="100" />
          <el-table-column label="订单金额" width="120">
            <template #default="scope">
              {{ scope.row.totalPay.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="payType" label="支付方式" width="100">
            <template #default="scope">
              <span v-if="scope.row.payType === '2'">未支付</span>
              <span v-else-if="scope.row.payType === '1'">支付宝支付</span>
              <span v-else-if="scope.row.payType === '0'">微信支付</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="订单状态" width="120">
            <template #default="scope">
              <el-tag v-if="scope.row.status === '0' || scope.row.status === 0" type="warning">未支付</el-tag>
              <el-tag v-else-if="scope.row.status === '1' || scope.row.status === 1" type="primary">待发货</el-tag>
              <el-tag v-else-if="scope.row.status === '2' || scope.row.status === 2" type="info">已发货</el-tag>
              <el-tag v-else-if="scope.row.status === '3' || scope.row.status === 3" type="success">待取货</el-tag>
              <el-tag v-else-if="scope.row.status === '4' || scope.row.status === 4" type="success">交易完成</el-tag>
              <el-tag v-else-if="scope.row.status === '-1' || scope.row.status === -1" type="danger">顾客取消</el-tag>
              <el-tag v-else-if="scope.row.status === '-2' || scope.row.status === -2" type="danger">超时关闭</el-tag>
              <el-tag v-else type="info">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="payTime" label="支付时间" width="180" />
          <el-table-column prop="createTime" label="订单提交时间" width="180" />
          <el-table-column fixed="right" label="操作" min-width="250">
            <template #default="scope">
              <el-button type="primary" :icon="CircleClose" @click="cancelOrder1(scope.row)"
                         v-if="scope.row.status === '0' || scope.row.status === 0" size="small">取消订单</el-button>
              <el-button type="success" :icon="Van" @click="fahuo(scope.row)" v-if="scope.row.status === '1' || scope.row.status === 1"
                         size="small">发货</el-button>
              <el-button type="success" :icon="Check" @click="daoda(scope.row)" v-if="scope.row.status === '2' || scope.row.status === 2"
                         size="small">确认送达</el-button>
              <el-button type="info" :icon="Pointer" @click="showOrder(scope.row)"
                         v-if="scope.row.status === '2' || scope.row.status === 2 ||scope.row.status === '3' || scope.row.status === 3 || scope.row.status === '4' || scope.row.status === 4" size="small">订单跟踪</el-button>
              <el-button type="danger" :icon="CircleClose" @click="deleteRow(scope.row)"
                         v-if="scope.row.status === '-1' || scope.row.status === -1 || scope.row.status === '-2' || scope.row.status === -2" size="small">删除订单</el-button>
              <el-button type="primary" :icon="Search" @click="lookOrder(scope.row)" size="small">查看订单</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="pagination" style="margin-top: 10px;">
        <el-pagination v-model:current-page="pi.pageNo" v-model:page-size="pi.pageSize"
                       :page-sizes="[5, 10, 15, 30, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pi.total"
                       background @current-change="handlePageChange" @size-change="handleSizeChange" />
      </div>
    </div>
    <el-dialog v-model="show" :title="title" width="400" draggable :close-on-click-modal="false">
      <el-timeline style="max-width: 600px; margin: 0 auto;" >
        <el-timeline-item v-for="(activity, index) in activities" :key="index" :icon="activity.icon"
                          :type="activity.type" :color="activity.color" :size="activity.size" :hollow="activity.hollow"
                          :timestamp="activity.timestamp">
          {{ activity.content }}
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script setup>
import { Select, Plus, Edit, Search, Refresh, Delete, CircleClose, CircleCheck, Pointer, Check, Van, SwitchButton, MoreFilled } from '@element-plus/icons-vue'
import { ref, onMounted, toRaw, nextTick } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { findAll, deleteById, save, update as updateOrder, deleteAll, cancelOrder, startOrder, songOrder } from '@/api/OrderApi';
import { fi } from 'element-plus/es/locales.mjs';
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const tableData = ref([]);
const show = ref(false);
const title = ref('');
const activities = ref([]);
const loading = ref(false);
const tableRef = ref();

// 分页信息
const pi = ref({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

// 搜索条件
const or = ref({
  orderNo: "",
})

onMounted(() => {
  search();
})

function showOrder(row) {
  let status = row.status;
  let updateTime = row.updateTime;
  let payTime = row.payTime;
  console.log(status);
  if (status === 4) {
    activities.value = [
      { content: '支付成功', timestamp: payTime, size: 'large', type: 'success',icon: Select },
      { content: '已发货', timestamp: '2024-09-12 20:48', size: 'large', type: 'success',icon: Select  },
      { content: '到达北京物流中转中心', timestamp: '2024-09-12 20:48', size: 'large', type: 'success',icon: Select  },
      { content: '到达西安物流中转中心', timestamp: '2024-09-12 20:48', size: 'large', type: 'success',icon: Select  },
      { content: '货已送达,等待取货', timestamp: '2024-09-12 10:20', size: 'large', type: 'success',icon: Select  },
      { content: '已取货，交易成功', timestamp: updateTime, size: 'large', type: 'success',icon: Select  }
    ];
  } else {
    activities.value = [
      { content: '支付成功', timestamp: payTime, size: 'large', type: 'success',icon: Select  },
      { content: '已发货', timestamp: '2024-09-12 20:48', size: 'large', type: 'success',icon: Select  },
      { content: '到达北京物流中转中心', timestamp: '2024-09-12 20:48', size: 'large', type: 'success',icon: Select  },
      { content: '到达西安物流中转中心', timestamp: '2024-09-12 20:48', size: 'large', type: 'success',icon: Select  },
      { content: '货已送达,等待取货', timestamp: updateTime, size: 'large', type: 'success',icon: Select },
      { content: '已取货，交易成功', timestamp: '', size: 'large', type: 'primary'  }
    ];
  }
  show.value = true;
}

async function search() {
  try {
    loading.value = true;
    let params = or.value;
    let resp = await findAll(pi.value.pageNo, pi.value.pageSize, params);
    console.log("API Response:", resp);

    if (resp && resp.records) {
      tableData.value = resp.records;
      console.log(tableData.value)
      pi.value = {
        pageNo: resp.current,
        pageSize: resp.size,
        total: resp.total
      };
    } else {
      console.warn("API返回数据格式不正确或请求失败:", resp);
      ElMessage({
        message: "数据格式不正确或请求失败",
        type: "warning",
      });
    }
  } catch (error) {
    console.error("获取后端服务器数据异常", error);
    ElMessage({
      message: `获取数据失败: ${error}`,
      type: "error",
      duration: 5000
    });
  } finally {
    loading.value = false;
  }
}

// 分页查询
function handlePageChange(page) {
  pi.value.pageNo = page;
  search();
}

function handleSizeChange(size) {
  pi.value.pageSize = size;
  pi.value.pageNo = 1; // 重置为第一页
  search();
}

function deleteRow(row) {
  let id = row.id;
  console.log(id);
  deleteOrder(id);
}

// 删除函数
function deleteOrder(id) {
  ElMessageBox.confirm("是否确认删除所选行?", "警告！", {
    type: "warning",
  })
      .then(async () => {
        try {
          let resp = await deleteById(id);
          if (resp.code === 200) {
            ElMessage({
              message: resp.msg,
              type: "success",
            });
            // 重新加载数据
            await search();
          } else {
            ElMessage({
              message: resp.msg,
              type: "error",
            });
          }
        } catch (error) {
          console.error("删除订单异常:", error);
          ElMessage({
            message: "删除失败，请稍后重试",
            type: "error",
          });
        }
      })
      .catch(() => { });
}

function deleteRows() {
  let rows = tableRef.value.getSelectionRows();
  console.log(rows);
  let ids = [];
  for (let row of rows) {
    ids.push(toRaw(row).id);
  }
  deleteAllRows(ids);
}

async function deleteAllRows(ids) {
  if (ids.length == 0) {
    ElMessage({
      message: "请选择想要删除的行",
      type: "warning",
    });
  } else {
    ElMessageBox.confirm("是否确认删除所选行?", "警告", {
      type: "warning",
    })
        .then(async () => {
          try {
            let resp = await deleteAll(ids);
            if (resp.code === 200) {
              ElMessage({
                message: resp.msg,
                type: "success",
              });
              await search();
            } else {
              ElMessage({
                message: resp.msg,
                type: "warning",
              });
            }
          } catch (error) {
            console.error("批量删除异常:", error);
            ElMessage({
              message: "删除失败，请稍后重试",
              type: "error",
            });
          }
        })
        .catch(() => { });
  }
}

async function cancelOrder1(row) {
  ElMessageBox.confirm("是否确认取消订单?", "警告", {
    type: "warning",
  }).then(async () => {
    try {
      let resp = await cancelOrder(row.id);
      if (resp.code === 200) {
        ElMessage({
          message: resp.msg,
          type: "success",
        });
        // 重新加载数据
        await search();
      } else {
        ElMessage({
          message: resp.msg || "操作失败",
          type: "warning",
        });
      }
    } catch (error) {
      console.error("取消订单异常:", error);
      ElMessage({
        message: "操作失败，请稍后重试",
        type: "error",
      });
    }
  })
      .catch(() => { });
}

async function fahuo(row) {
  ElMessageBox.confirm("是否确认发货?", {
    type: "success",
  }).then(async () => {
    try {
      let resp = await startOrder(row.id);
      if (resp.code == 200) {
        ElMessage({
          message: resp.msg,
          type: "success",
        });
        await search();
      } else {
        ElMessage({
          message: resp.msg || "操作失败",
          type: "warning",
        });
      }
    } catch (error) {
      console.error("发货异常:", error);
      ElMessage({
        message: "操作失败，请稍后重试",
        type: "error",
      });
    }
  })
      .catch(() => { });
}

async function daoda(row) {
  ElMessageBox.confirm("是否确认送达?", {
    type: "success",
  }).then(async () => {
    try {
      let resp = await songOrder(row.id);
      if (resp.code === "200") {
        ElMessage({
          message: resp.msg,
          type: "success",
        });
        await search();
      } else {
        ElMessage({
          message: resp.msg || "操作失败",
          type: "warning",
        });
      }
    } catch (error) {
      console.error("确认送达异常:", error);
      ElMessage({
        message: "操作失败，请稍后重试",
        type: "error",
      });
    }
  })
      .catch(() => { });
}

function lookOrder(row) {
  router.push({
    name: 'orderDetail',
    params: { id: row.id }
  });
}
</script>

<style scoped>
.main {
  padding: 0 20px;
}

.data>.pagination {
  margin-top: 10px;
  float: right;
}

.data {
  margin-top: 20px;
}

.search {
  margin-top: 10px;
  margin-bottom: 10px;
  padding: 20px;
  border: 1px solid #ebeef5;
  margin-top: 20px;
}

.mid {
  margin-top: 10px;
  margin-bottom: 10px;
  padding: 20px;
  border: 1px solid #ebeef5;
  margin-top: 20px;
  height: 50px;
}

.search>.button {
  float: right;
}

.el-table td.is-center,
.el-table th.is-center {
  text-align: center;
}

.el-table td,
.el-table th {
  padding: 12px 0;
  min-width: 0;
  box-sizing: border-box;
  text-overflow: ellipsis;
  vertical-align: middle;
  position: relative;
}
</style>